package com.learning.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.learning.constant.MessageConstant;
import com.learning.context.BaseContext;
import com.learning.dto.QuestionDetailDTO;
import com.learning.dto.QuestionPageQueryDTO;
import com.learning.entity.*;
import com.learning.exceptiom.PermissionErrorException;
import com.learning.mapper.QuestionMapper;
import com.learning.result.PageResult;
import com.learning.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learning.vo.QuestionDetailVO;
import com.learning.vo.QuestionVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 题目表 服务实现类
 * </p>
 *
 * @author itRao
 * @since 2024-05-24
 */
@Service
@AllArgsConstructor
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    private final IAnswerService answerService;
    private final IKnowledgeService knowledgeService;
    private final IChaptersService chaptersService;
    private final IPermissionService permissionService;


    @Override
    public PageResult<QuestionVO> pageQuery(QuestionPageQueryDTO dto) {
        Page<Question> page = lambdaQuery()
                .eq(dto.getType() != null, Question::getType, dto.getType())
                .eq(dto.getDifficulty() != null, Question::getDifficulty, dto.getDifficulty())
                .page(Page.of(dto.getPage(), dto.getPageSize()));

        List<Question> questionList = page.getRecords();

        List<QuestionVO> vos = new ArrayList<>();

        for (Question question : questionList) {
            QuestionVO vo = BeanUtil.copyProperties(question, QuestionVO.class);
            vos.add(vo);
        }

        return new PageResult<QuestionVO>(page.getTotal(), page.getPages(), vos);
    }

    @Override
    public QuestionDetailVO queryDetail(Long id) {
        QuestionDetailVO vo = new QuestionDetailVO();

        vo.setQuestionId(id);

        Question question = lambdaQuery().eq(Question::getId, id).one();
        if (question == null) {
            return null;
        }
        BeanUtils.copyProperties(question, vo);

        vo.setDifficulty(question.getDifficulty().getValue());
        vo.setType(question.getType().getValue());

        Answer answer = answerService.lambdaQuery().eq(Answer::getQuestionId, id).one();
        BeanUtils.copyProperties(answer, vo);
        vo.setAnswerId(answer.getId());

        Knowledge knowledge = knowledgeService.lambdaQuery().eq(Knowledge::getQuestionId, id).one();
        BeanUtils.copyProperties(knowledge, vo);
        vo.setKnowledgeId(knowledge.getId());

        Chapters chapters = chaptersService.lambdaQuery().eq(Chapters::getQuestionId, id).one();
        BeanUtils.copyProperties(chapters, vo);
        vo.setChaptersId(chapters.getId());

        return vo;
    }

    @Override
    @Transactional
    public void saveQuestion(QuestionDetailDTO dto) {
        //判断该教师是否具有新增问题的权限

        Long teacherId = BaseContext.getCurrentId();
        Permission permission = permissionService.lambdaQuery().eq(Permission::getTeacherId, teacherId).one();

        if (!permission.getInsertAuth()) {
            throw new PermissionErrorException(MessageConstant.PERMISSION_ERROR);
        }

        questionInsert(dto);
    }

    @Override
    @Transactional
    public void updateQuestion(QuestionDetailDTO dto) {
        //判断该教师是否具有修改问题的权限

        Long teacherId = BaseContext.getCurrentId();
        Permission permission = permissionService.lambdaQuery().eq(Permission::getTeacherId, teacherId).one();

        if (!permission.getUpdateAuth()) {
            throw new PermissionErrorException(MessageConstant.PERMISSION_ERROR);
        }

        //先删除后插入
        Long id = dto.getId();

        questionDelete(id);

        questionInsert(dto);
    }

    @Override
    public void deleteQuestion(Long id) {
        //判断该教师是否具有删除问题的权限
        Long teacherId = BaseContext.getCurrentId();
        Permission permission = permissionService.lambdaQuery().eq(Permission::getTeacherId, teacherId).one();

        if (!permission.getDeleteAuth()) {
            throw new PermissionErrorException(MessageConstant.PERMISSION_ERROR);
        }

        questionDelete(id);
    }

    /**
     * 删除问题
     *
     * @param id
     */
    private void questionDelete(Long id) {
        removeById(id);
        answerService.lambdaUpdate().eq(Answer::getQuestionId, id).remove();
        knowledgeService.lambdaUpdate().eq(Knowledge::getQuestionId, id).remove();
        chaptersService.lambdaUpdate().eq(Chapters::getQuestionId, id).remove();
    }

    /**
     * 上传题目详细
     *
     * @param dto
     */
    //TODO 上传贴图问题
    private void questionInsert(QuestionDetailDTO dto) {
        Question question = BeanUtil.copyProperties(dto, Question.class);
        save(question); //MybatisPlus
        Long questionId = question.getId();

        Answer answer = BeanUtil.copyProperties(dto, Answer.class);
        answer.setQuestionId(questionId);
        answerService.save(answer);

        Knowledge knowledge = BeanUtil.copyProperties(dto, Knowledge.class);
        knowledge.setQuestionId(questionId);
        knowledgeService.save(knowledge);

        Chapters chapters = BeanUtil.copyProperties(dto, Chapters.class);
        chapters.setQuestionId(questionId);
        chaptersService.save(chapters);
    }
}
